package udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class UdpEchoServer {
    private DatagramSocket socket = null;

    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);   //port:端口号
    }

    public void start() throws IOException {
        System.out.println("服务器启动!");
        while (true) {
            //每次循环,就是一个请求-响应过程
            //1.读取请求并解析
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(requestPacket);
            //基于字节数组构造String
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength());
            //2.根据请求计算响应(对于回显服务器来说,这一步啥都不做)
            String response = process(request);
            //把响应返回客户端
            // 构造一个 DatagramPacke 作为相应对象
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),
                    0, response.getBytes().length,
                    requestPacket.getSocketAddress()); //得到 INetAddress 对象, 这个对象包含了 ip 和端口号
            socket.send(responsePacket);

            //打印日志
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateTime = sdf.format(calendar.getTime());
            System.out.printf("[%s:%d time:%s] req: %s, resp: %s\n", requestPacket.getAddress().toString(),
                    requestPacket.getPort(),dateTime, request, response);
        }
    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server = new UdpEchoServer(9090);
        server.start();
    }
}

